package com.jzo2o.foundations.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeItemResDTO;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServeItemPageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeItemUpsertReqDTO;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.chrono.MinguoDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeMapper serverMapper;
    @Autowired
    private ServeItemMapper serverItemMapper;
    @Autowired
    private RegionMapper regionMapper;


    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO dto) {

        return PageHelperUtils.selectPage(dto,
                () -> baseMapper.queryList(dto.getRegionId()));
    }

    @Override
    public void add(List<ServeUpsertReqDTO> listDto) {

        List<Long> ids = listDto.stream().map(ServeUpsertReqDTO::getServeItemId).collect(Collectors.toList());
        List<ServeItem> serverItems = serverItemMapper.selectBatchIds(ids);
        Long itemDisableCount = serverItems.stream().filter(si->si.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()).count();
        if (itemDisableCount > 0) {
            throw new ForbiddenOperationException("存在不可用服务");
        }

        Integer count = lambdaQuery()
                .in(Serve::getServeItemId, ids)
                .eq(Serve::getRegionId, listDto.get(0).getRegionId())
                .count();
        if (count > 0) {
            throw new ForbiddenOperationException("服务重复添加");
        }

        Region region = regionMapper.selectById(listDto.get(0).getRegionId());

        List<Serve> list = listDto.stream().map(dto -> {
            Serve serve = BeanUtils.copyBean(dto, Serve.class);
            serve.setCityCode(region.getCityCode());
            return serve;
        }).collect(Collectors.toList());

        saveBatch(list);

    }

    @Override
    public void editPrice(Long id, BigDecimal price) {
        Serve serve = serverMapper.getServeById(id);
        if (serve == null) {
            throw new CommonException("价格修改失败，因为服务不存在");
        }
        serve.setPrice(price);
        serverMapper.updateById(serve);
    }

    @Override
    public void editStatus(Long id) {
        Serve serve = serverMapper.getServeById(id);
        if (serve == null) {
            throw new CommonException("服务上架失败，因为服务不存在");
        }
        Integer saleStatus = serve.getSaleStatus();
        if (!(saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.DISABLE.getStatus())) {
            throw new CommonException("服务上架失败，因为服务状态不符合上架要求");
        }
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serverItemMapper.getServeItemById(serveItemId);
        if (serveItem == null) {
            throw new CommonException("服务上架失败，因为服务项目不存在");
        }
        Integer activeStatus = serveItem.getActiveStatus();
        if (activeStatus != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new CommonException("服务上架失败，因为服务项目不是启动状态");
        }

        serve.setSaleStatus(FoundationStatusEnum.ENABLE.getStatus());
        serverMapper.updateById(serve);
    }

    @Override
    public void delete(Long id) {
        Serve serve = serverMapper.selectById(id);
        if (serve == null) {
            throw new CommonException("服务删除失败，因为服务不存在");

        }
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new CommonException("服务删除失败，因为服务没有下架");
        }
        serverMapper.deleteById(id);
    }

    @Override
    public void offStatus(Long id) {
        Serve serve = serverMapper.getServeById(id);
        if (serve == null) {
            throw new CommonException("服务下架失败，因为服务不存在");
        }
        Integer saleStatus = serve.getSaleStatus();
        if (saleStatus != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new CommonException("服务下架失败，因为服务状态不符合下架要求");
        }
        Long serveItemId = serve.getServeItemId();
//        ServeItem serveItem = serverItemMapper.getServeItemById(serveItemId);
//        if (serveItem == null) {
//            throw new CommonException("服务下架失败，因为服务项目不存在");
//        }
//        Integer activeStatus = serveItem.getActiveStatus();
//        if (!(activeStatus==FoundationStatusEnum.ENABLE.getStatus())) {
//            throw new CommonException("服务下架失败，因为服务项目不是启动状态");
//        }

        serve.setSaleStatus(FoundationStatusEnum.DISABLE.getStatus());
        serverMapper.updateById(serve);
    }

    @Override
    public void changeHotStatus(Long id, int flag) {
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, flag)
                .set(Serve::getHotTimeStamp, System.currentTimeMillis());
        super.update(updateWrapper);
    }

    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long id, int status) {
        LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getRegionId, id)
                .eq(ObjectUtil.isNotEmpty(status), Serve::getSaleStatus, status);
        return baseMapper.selectCount(queryWrapper);
    }
}
